<?php

namespace app\api\model;

use think\Model;

class Address extends Model
{
    protected $hidden = ['mp_id','user_id', 'modify_time'];

    //添加或修改地址信息
    public function addOrEdit($data)
    {
        //改变默认地址
        if (isset($data['default']) && $data['default'] == 1)
            self::where('user_id', $data['user_id'])->update(['default' => 0]);

        if(empty($data['id'])){
            $res = $this->allowField(true)->save($data);
        }else{
            $res = $this->allowField(true)->save($data,['id'=>$data['id'],'user_id'=>$data['user_id']]);
        }
        if ($res > 0)
            return ['_code' => 201, 'msg' => '保存成功'];
        else
            return ['_code' => 500, 'msg' => '保存失败!'];
    }

    //获取地址快照信息
    public static function getUserAddress($userId,$addrId)
    {
        $map = [
            'user_id' => $userId,
            'id' => $addrId
        ];
        $address = self::get($map);
        if ($address) {
            $addrSnap = $address['name']
                . '-' . $address['phone']
                . '-' . $address['province'] . $address['city'] . $address['town'] . $address['address'];
            return $addrSnap;
        } else {
            return false;
        }
    }

    public static function getByUid($uid)
    {
        $addrList = self::where('user_id', $uid)
            ->order('id desc')
            ->select();
        return $addrList;
    }

    //添加或修改地址信息
    public static function deleteById($id,$uid)
    {
        $res = self::destroy(['id'=>$id,'user_id'=>$uid]);
        if ($res > 0)
            return ['_code' => 201, 'msg' => '删除成功!'];
        else
            return ['_code' => 500, 'msg' => '删除失败!'];
    }
}
